/**
 * Copyright (c) 2011, JFXtras
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package jfxtras.scene.control;

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventTarget;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.util.Callback;
import javafx.util.StringConverter;

/**
 * This is a spinner, showing one value at a time.
 * Basically a spinner shows a list of values and can do "next" or "previous" on this.
 * But not all values can or should be offered to the spinner in the form of a list, because of -for example- memory consumption.
 * For this the spinner has a SpinnerXDataProvider as the core model, it has methods for determining what is next or previous.
 * SpinnerX itself has some conveniences constructors.
 * 
 * SpinnerX can be editable, the user can then type a value instead of selecting it.
 * Such a typed value is provided to the DataProvider to determine where in its domain it exists.
 * If the value does not exist, the DataProvider is asked to add it to the domain. 
 * If the DataProvider refuses, this will cause the value to not be accepted and the previous value is shown again. 
 * 
 * @author Tom Eugelink
 */
public class SpinnerX<T> extends Control
{
	// ==================================================================================================================
	// CONSTRUCTOR

	/**
	 */
	public SpinnerX()
	{
		construct();
	}

	// ------------
	// model
	
	/**
	 * @param model
	 * @param startValue
	 */
	public SpinnerX(SpinnerXDataProvider<T,? extends Object> model)
	{
		setDataProvider(model);
		first();
		construct();
	}

	/**
	 * @param model
	 * @param startValue
	 */
	public SpinnerX(SpinnerXDataProvider<T,? extends Object> model, T startValue)
	{
		setDataProvider(model);
		setValue(startValue);
		construct();
	}

	// ------------
	// array
	
	/**
	 * 
	 * @param list
	 */
	public SpinnerX(T... list)
	{
		this( SpinnerXDataProviderList.list(list) );
	}

	/**
	 * 
	 * @param startIdx
	 * @param list
	 */
	public SpinnerX(int startIdx, T... list)
	{
		setDataProvider( SpinnerXDataProviderList.list(list) );
		if (startIdx >= 0) setValue(list[startIdx]);
		construct();
	}
	
	// ------------
	
	/*
	 * 
	 */
	private void construct()
	{
		// setup the CSS
		// the -fx-skin attribute in the CSS sets which Skin class is used
		this.getStyleClass().add(this.getClass().getSimpleName().toLowerCase());
	}

	/**
	 * Return the path to the CSS file so things are setup right
	 */
	@Override protected String getUserAgentStylesheet()
	{
		return this.getClass().getResource(this.getClass().getSimpleName() + ".css").toString();
	}
	
	// ==================================================================================================================
	// PROPERTIES
	
	/** Value: */
	public ObjectProperty<T> valueProperty() { return this.valueObjectProperty; }
	final private ObjectProperty<T> valueObjectProperty = new SimpleObjectProperty<T>(this, "value", null);
	// java bean API
	public T getValue() { return this.valueObjectProperty.getValue(); }
	public void setValue(T value) { this.valueObjectProperty.setValue(value); }
	public SpinnerX<T> withValue(T value) { setValue(value); return this; }

	/** Cyclic: */
	public ObjectProperty<Boolean> cyclicProperty() { return this.cyclicObjectProperty; }
	final private ObjectProperty<Boolean> cyclicObjectProperty = new SimpleObjectProperty<Boolean>(this, "cyclic", false);
	// java bean API
	public Boolean isCyclic() { return this.cyclicObjectProperty.getValue(); }
	public void setCyclic(Boolean value) { this.cyclicObjectProperty.setValue(value); }
	public SpinnerX<T> withCyclic(Boolean value) { setCyclic(value); return this; }

	/** Editable: */
	public ObjectProperty<Boolean> editableProperty() { return this.editableObjectProperty; }
	final private ObjectProperty<Boolean> editableObjectProperty = new SimpleObjectProperty<Boolean>(this, "editable", false);
	// java bean API
	public Boolean isEditable() { return this.editableObjectProperty.getValue(); }
	public void setEditable(Boolean value) { this.editableObjectProperty.setValue(value); }
	public SpinnerX<T> withEditable(Boolean value) { setEditable(value); return this; }

	/** DataProvider: */
	public ObjectProperty<SpinnerXDataProvider<T,? extends Object>> dataProviderProperty() { return this.dataProviderObjectProperty; }
	final private ObjectProperty<SpinnerXDataProvider<T,? extends Object>> dataProviderObjectProperty = new SimpleObjectProperty<SpinnerXDataProvider<T,? extends Object>>(this, "dataProvider", null);
	// java bean API
	public SpinnerXDataProvider<T,? extends Object> getDataProvider() { return this.dataProviderObjectProperty.getValue(); }
	public void setDataProvider(SpinnerXDataProvider<T,? extends Object> value) { this.dataProviderObjectProperty.setValue(value); }
	public SpinnerX<T> withDataProvider(SpinnerXDataProvider<T,? extends Object> value) { setDataProvider(value); return this; }

	/** CellFactory: */
	public ObjectProperty<Callback<SpinnerX<T>, Node>> cellFactoryProperty() { return this.cellFactoryObjectProperty; }
	final private ObjectProperty<Callback<SpinnerX<T>, Node>> cellFactoryObjectProperty = new SimpleObjectProperty<Callback<SpinnerX<T>, Node>>(this, "cellFactory", new DefaultCellFactory());
	// java bean API
	public Callback<SpinnerX<T>, Node> getCellFactory() { return this.cellFactoryObjectProperty.getValue(); }
	public void setCellFactory(Callback<SpinnerX<T>, Node> value) { this.cellFactoryObjectProperty.setValue(value); }
	public SpinnerX<T> withCellFactory(Callback<SpinnerX<T>, Node> value) { setCellFactory(value); return this; }

	/** StringConverter<T>: */
	public ObjectProperty<StringConverter<T>> stringConverterProperty() { return this.stringConverterObjectProperty; }
	final private ObjectProperty<StringConverter<T>> stringConverterObjectProperty = new SimpleObjectProperty<StringConverter<T>>(this, "stringConverter", new DefaultStringConverter());
	// java bean API
	public StringConverter<T> getStringConverter() { return this.stringConverterObjectProperty.getValue(); }
	public void setStringConverter(StringConverter<T> value) { this.stringConverterObjectProperty.setValue(value); }
	public SpinnerX<T> withStringConverter(StringConverter<T> value) { setStringConverter(value); return this; }

	/** ArrowDirection: */
	public ObjectProperty<ArrowDirection> arrowDirectionProperty() { return this.arrowDirectionObjectProperty; }
	final private ObjectProperty<ArrowDirection> arrowDirectionObjectProperty = new SimpleObjectProperty<ArrowDirection>(this, "arrowDirection", ArrowDirection.HORIZONTAL);
	// java bean API
	public ArrowDirection getArrowDirection() { return this.arrowDirectionObjectProperty.getValue(); }
	public void setArrowDirection(ArrowDirection value) { this.arrowDirectionObjectProperty.setValue(value); }
	public SpinnerX<T> withArrowDirection(ArrowDirection value) { setArrowDirection(value); return this; }
	public enum ArrowDirection {VERTICAL, HORIZONTAL}
	
	// ==================================================================================================================
	// StringConverter
	
	/**
	 * A string converter that does a simple toString, but cannot convert to an object
	 * @see org.jfxextras.util.StringConverterFactory 
	 */
	class DefaultStringConverter extends StringConverter<T>
	{
		@Override
		public T fromString(String string)
		{
			throw new IllegalStateException("not implemented");
		}

		@Override
		public String toString(T value)
		{
			return value == null ? "" : value.toString();
		}
	}
	
	// ==================================================================================================================
	// CellFactory
	
	/**
	 * Default cell factory
	 */
	class DefaultCellFactory implements Callback<SpinnerX<T>, Node>
	{
		private Label label = null;
		
		@Override
		public Node call(SpinnerX<T> spinner)
		{
			// get value
			T lValue = spinner.getValue();
			
			// label not yet created
			if (this.label == null) 
			{
				this.label = new Label();
			}
			this.label.setText( lValue == null ? "" : getStringConverter().toString(lValue) );
			return this.label;
		}
	};
	
	// ==================================================================================================================
	// EVENTS
	
	/** OnCycle: */
	public ObjectProperty<EventHandler<CycleEvent>> onCycleProperty() { return iOnCycleObjectProperty; }
	final private ObjectProperty<EventHandler<CycleEvent>> iOnCycleObjectProperty = new SimpleObjectProperty<EventHandler<CycleEvent>>(null);
	// java bean API
	public EventHandler<CycleEvent> getOnCycle() { return iOnCycleObjectProperty.getValue(); }
	public void setOnCycle(EventHandler<CycleEvent> value) { iOnCycleObjectProperty.setValue(value); }
	public SpinnerX<T> withOnCycle(EventHandler<CycleEvent> value) { setOnCycle(value); return this; }
	final static public String ONCYCLE_PROPERTY_ID = "onCycle";
	
	/**
	 * CycleEvent 
	 */
	static public class CycleEvent extends Event
	{
		/**
		 * 
		 */
		public CycleEvent()
		{
			super(new EventType<CycleEvent>());
		}

		/**
		 * 
		 * @param source
		 * @param target
		 */
		public CycleEvent(Object source, EventTarget target)
		{
			super(source, target, new EventType<CycleEvent>());
		}
		
		public Object getOldIdx() { return this.oldIdx; }
		private Object oldIdx;
		
		public Object getNewIdx() { return this.newIdx; }
		private Object newIdx;
		
		
		public boolean cycledDown() { return cycleDirection == CycleDirection.TOP_TO_BOTTOM; }
		public boolean cycledUp() { return cycleDirection == CycleDirection.BOTTOM_TO_TOP; }
		CycleDirection cycleDirection;
	}
	
	/**
	 * we're cycling, fire the event
	 */
	public void fireCycleEvent(CycleDirection cycleDirection)
	{
		EventHandler<CycleEvent> lCycleEventHandler = getOnCycle();
		if (lCycleEventHandler != null)
		{
			CycleEvent lCycleEvent = new CycleEvent();
			lCycleEvent.cycleDirection = cycleDirection;
			lCycleEventHandler.handle(lCycleEvent);
		}
	}
	static public enum CycleDirection { TOP_TO_BOTTOM, BOTTOM_TO_TOP }
	
	
	// ==================================================================================================================
	// BEHAVIOR

	/**
	 * 
	 */
	public void first()
	{
		// get the dataprovider
		SpinnerXDataProvider lDataProvider = getDataProvider(); 
		if (lDataProvider != null) 
		{		
			// get the first index
			Object lIdx = lDataProvider.getPreviousIndex(null);
				
			// get the value for this index
			T lValue = (T)lDataProvider.getValue(lIdx);
			
			// set it
			setValue(lValue);
		}
	}
	
	/**
	 * 
	 */
	public void previous()
	{
		// get the dataprovider
		SpinnerXDataProvider lDataProvider = getDataProvider(); 
		if (lDataProvider != null) 
		{
			// get the current index
			Object lOldIdx = lDataProvider.getIndex(getValue());
						
			// get the previous index (usually current - 1)
			Object lIdx = lDataProvider.getPreviousIndex(lOldIdx);
			
			// if null is return, there is no previous index
			if (lIdx == null)
			{
				// if we're not cyclic
				if (isCyclic() != null && isCyclic().booleanValue() == false)
				{
					// do nothing
					return;
				}
				
				// cycle to the other end: get the last value
				lIdx = lDataProvider.getNextIndex(null);
				
				// notify listener that we've cycled
				fireCycleEvent(CycleDirection.BOTTOM_TO_TOP);
			}
			
			// get the value for the new index
			T lValue = (T)lDataProvider.getValue(lIdx);
			
			// set it
			setValue(lValue);
		}
	}
	
	/**
	 * 
	 */
	public void next()
	{
		// get the data provider
		SpinnerXDataProvider lDataProvider = getDataProvider(); 
		if (lDataProvider != null) 
		{			
			// get the current index
			Object lOldIdx = lDataProvider.getIndex(getValue());
			
			// get the next index (usually current + 1)
			Object lIdx = lDataProvider.getNextIndex(lOldIdx);
			
			// if null is return, there is no next index (usually current + 1)
			if (lIdx == null)
			{
				// if we're not cyclic
				if (isCyclic() != null && isCyclic().booleanValue() == false)
				{
					// do nothing
					return;
				}
				
				// cycle to the other end: get the first value
				lIdx = lDataProvider.getPreviousIndex(null);
				
				// notify listener that we've cycled
				fireCycleEvent(CycleDirection.TOP_TO_BOTTOM);
			}
			
			// get the value of the new index
			T lValue = (T)lDataProvider.getValue(lIdx);
			
			// set the value
			setValue(lValue);
		}
	}

	/**
	 * Get the last index; if the data provide is endless, this method mail fail!
	 */
	public void last()
	{
		// get the dataprovider
		SpinnerXDataProvider lDataProvider = getDataProvider(); 
		if (lDataProvider != null) 
		{			
			// get the last index
			Object lIdx = lDataProvider.getNextIndex(null);
				
			// get the value for this index
			T lValue = (T)lDataProvider.getValue(lIdx);
			
			// set it
			setValue(lValue);
		}
	}
	
}
